package test

import (
	"gin-demo/common"
	"gin-demo/container"
	"gin-demo/entity"
	"gorm.io/gorm"
	"time"
)

type TestDaoImp struct {
}

func (t *TestDaoImp) List(pageRequest common.PageRequest) (*entity.TestList, error) {

	var tests []*entity.Test

	var count int64
	var testDB = container.Get("db").(*gorm.DB)
	now := time.Now().Unix()
	timeThreshold := now - 1*60
	err := testDB.
		Model(entity.Test{}).
		Where("update_time > ?", timeThreshold).
		Find(&tests).Error
	if err != nil {
		return nil, err
	}
	err = testDB.
		Model(entity.Test{}).
		Where("update_time > ?", timeThreshold).
		Count(&count).Error
	if err != nil {
		return nil, err
	}
	var pageResponse common.PageResponse
	pageResponse.Total = count
	pageResponse.PageInfo = pageRequest
	testList := &entity.TestList{
		PageResponse: pageResponse,
		Tests:        tests,
	}
	return testList, nil

}

func (t *TestDaoImp) Create(test *entity.Test) (*entity.Test, error) {

	var testDB = container.Get("db").(*gorm.DB)
	err := testDB.
		Model(entity.Test{}).
		Create(&test).Error
	if err != nil {
		return nil, err
	}
	return test, nil
}
